package com.hruiworks.campusgroup.controller;

import com.hruiworks.campusgroup.pojo.entity.User;
import com.hruiworks.campusgroup.service.SseService;
import com.hruiworks.campusgroup.utils.AuthorityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/sse")
public class SseController {


    @Resource
    private SseService sseService;

    @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter handleEvent(HttpServletRequest httpServletRequest) {
        User user = AuthorityUtils.currentUser(httpServletRequest);
        return sseService.sseConnect(user);
    }

    @GetMapping("/disconnect")
    public void disconnect(HttpServletRequest httpServletRequest) {
        User user = AuthorityUtils.currentUser(httpServletRequest);
        sseService.disconnect(user);
    }
}

